/**
 * Copyright 2016 JustWayward Team
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hzf.booklibrary;

import android.app.Application;
import android.content.Context;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;
import com.hzf.booklibrary.api.TokenApi;
import com.hzf.booklibrary.api.TokenApiService;
import com.hzf.booklibrary.api.device.DeviceApi;
import com.hzf.booklibrary.base.Constant;
import com.hzf.booklibrary.base.CrashHandler;
import com.hzf.booklibrary.bean.clazz.Clazz;
import com.hzf.booklibrary.bean.device.Deviceinfo;
import com.hzf.booklibrary.bean.token.TokenBean;
import com.hzf.booklibrary.component.AppComponent;
import com.hzf.booklibrary.component.DaggerAppComponent;
import com.hzf.booklibrary.manager.CacheManager;
import com.hzf.booklibrary.module.AppModule;
import com.hzf.booklibrary.module.BookApiModule;
import com.hzf.booklibrary.utils.AppUtils;
import com.hzf.booklibrary.utils.NetworkUtils;
import com.hzf.booklibrary.utils.SharedPreferencesUtil;
import com.hzf.booklibrary.utils.ToastUtils;
import com.tencent.bugly.Bugly;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author yuyh.
 * @date 2016/8/3.
 */
public class ReaderApplication extends Application {

    private static ReaderApplication sInstance;
    private AppComponent appComponent;
    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;
        initCompoent();
        AppUtils.init(this);
//        setupDataBase();
        CrashHandler.getInstance().init(this);
        initPrefs();
        Bugly.init(getApplicationContext(), "d7cac7feca", false);
        Utils.init(this);
        clearBookCache();
        getToken();
    }

    /**
     * 获取系统的token
     */
    private void getToken() {
        Retrofit build = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Constant.API_BASE_URL)
                .build();
        TokenApiService tokenApiService = build.create(TokenApiService.class);
        tokenApiService.getToken(Constant.CLIENT_ID_VALUE, Constant.CLIENT_SECRET_VALUE)
                .enqueue(new Callback<TokenBean>() {
                    @Override
                    public void onResponse(Call<TokenBean> call, Response<TokenBean> response) {
                        String token = response.body().getData().getToken();
                        SharedPreferencesUtil.getInstance().putString("token", token);
                        LogUtils.i("接收到服务器的token是:==" + token);
                        getDeviceInfo(token);
                    }

                    @Override
                    public void onFailure(Call<TokenBean> call, Throwable t) {

                    }
                });
    }

    /**
     * 获取设备的信息
     * @param token
     */
    public void getDeviceInfo(final String token) {
        DeviceApi.getInstance().getDeviceInfo(token, NetworkUtils.getWifiMac())
                .enqueue(new Callback<Deviceinfo>() {
                    @Override
                    public void onResponse(Call<Deviceinfo> call, Response<Deviceinfo> response) {
                        Deviceinfo.DataBean data = response.body().getData();
                        String deviceId = response.body().getData().getDeviceId();
                        String deviceOrgid = response.body().getData().getDeviceOrgid();

                        SharedPreferencesUtil.getInstance().putString("deviceId", deviceId);
                        SharedPreferencesUtil.getInstance().putString("deviceOrgid", deviceOrgid);

                        getClazzInfo(token,deviceId);
                    }

                    @Override
                    public void onFailure(Call<Deviceinfo> call, Throwable t) {
                        ToastUtils.showToast("网络错误,请检查网络");
                    }
                });




    }

    /**
     * 获取班级信息
     */
    public void getClazzInfo(String token,String deviceId){
        TokenApi.getInstance().getClazzInfo(token,deviceId)
                .enqueue(new Callback<Clazz>() {
                    @Override
                    public void onResponse(Call<Clazz> call, Response<Clazz> response) {
                        int classNumber = response.body().getData().getClassNumber();
                        SharedPreferencesUtil.getInstance().putInt("classNumber",classNumber);
                        LogUtils.i("获取的班级编号是:"+classNumber);
                    }

                    @Override
                    public void onFailure(Call<Clazz> call, Throwable t) {

                    }
                });
    }




    private void clearBookCache() {
        long bookCacheSize = CacheManager.getInstance().getBookCacheSize();

        LogUtils.i("缓存字节：" + CacheManager.getInstance().getCacheSize());
        //当图书缓存大于512M时，清理缓存
        if (bookCacheSize > 536870912) {
            CacheManager.getInstance().clearCache(false, true);//清除图书和阅读缓存
        }
    }

    public static ReaderApplication getsInstance() {
        return sInstance;
    }

    private void initCompoent() {
        appComponent = DaggerAppComponent.builder()
                .bookApiModule(new BookApiModule())
                .appModule(new AppModule(this))
                .build();
    }

    public AppComponent getAppComponent() {
        return appComponent;
    }

    /**
     * 初始化SharedPreference
     */
    protected void initPrefs() {
        SharedPreferencesUtil.init(getApplicationContext(), getPackageName() + "_preference", Context.MODE_APPEND);
    }

    public void initIpAdress() {

    }


//    public void setupDataBase(){
//        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this, Constant.DATABASENAME);
//        Database db = devOpenHelper.getWritableDb();
//        DaoMaster daoMaster = new DaoMaster(db);
//        daoSession = daoMaster.newSession();
//    }

//    public static DaoSession getDaoSession(){
//        return daoSession;
//    }

}
